
import store from '@/store'

/**
 * 字符权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function checkPermi(value) {
  if (!value) {
    console.error(`need roles! Like checkPermi="['system:user:add','system:user:edit'] || 'system:user:add'"`)
    return false
  }
  const permissions = store.getters && store.getters.permissions
  const allPermissions = store.getters && store.getters.allPermissions
  if (value instanceof Array && value.length > 0) {
    const permissionDatas = new Set(value)
    // const all_permission = '*:*:*' //当拥有的权限标识里有该标识时。默认拥有全部权限
    const hasAllPermission = Array.from(allPermissions).some(permission => {
      return permissionDatas.has(permission)
    })
    if (!hasAllPermission) { // 全部权限里未找到该标识。默认为拥有权限
      return true
    }

    const hasPermission = Array.from(permissions).some(permission => {
      return permissionDatas.has(permission)
      // return all_permission === permission || permissionDatas.has(permission)
    })

    if (!hasPermission) {
      return false
    }
    return true
  } else if (value && typeof value === 'string') {
    if (!allPermissions.has(value)) { // 全部权限里未找到该标识。默认为拥有权限
      return true
    }
    return permissions.has(value)
  } else {
    console.error(`need roles! Like checkPermi="['system:user:add','system:user:edit'] || 'system:user:edit'"`)
    return false
  }
}

/**
 * 角色权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function checkRole(value) {
  if (!value) {
    console.error(`need roles! Like checkRole="['admin','editor'] || 'admin'"`)
    return false
  }
  const roles = store.getters && store.getters.roles

  if (value instanceof Array && value.length > 0) {
    const permissionRoles = new Set(value)
    const super_admin = 'admin'

    const hasRole = Array.from(roles).some(role => {
      return super_admin === role || permissionRoles.has(role)
    })

    if (!hasRole) {
      return false
    }
    return true
  } else if (value && typeof value === 'string') {
    return roles.has(value)
  } else {
    console.error(`need roles! Like checkRole="['admin','editor']" || 'admin'`)
    return false
  }
}

